package com.zxt.example.mvc.zcommon.consumer;

import com.alibaba.fastjson.JSONObject;
import com.mchange.lang.ThrowableUtils;
import com.rabbitmq.client.Channel;
import com.zxt.mq.config.rabbitmq.RabbitData;
import com.zxt.mq.consumer.BaseConsumer;
import com.zxt.mq.consumer.DynamicConsumerContainerFactory;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.nio.charset.StandardCharsets;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 消费者具体定义方法
 * </p>
 *
 * @author zxt
 * @since 2022/7/22 11:32
 */
@Slf4j
public class DynamicConsumer {

    private final SimpleMessageListenerContainer container;

    public DynamicConsumer(DynamicConsumerContainerFactory dcf, String name) {
        container = dcf.getObject();
        if (ObjectUtil.isNotNull(container)) {
            container.setMessageListener(new BaseConsumer() {
                @Override
                public boolean process(Message message, Channel channel) {
                    log.info("DynamicConsumer{}{}{}", name, dcf.getQueue(), new String(message.getBody()));
                    distributionConsumerMsg(message, channel);
                    return true;
                }
            });
        }
    }

    /**
     * 启动消费者监听
     */
    public void start() {
        container.start();
    }

    /**
     * 消费者停止监听
     */
    public void stop() {
        container.stop();
    }

    /**
     * 消费者关闭
     */
    public void shutdown() {
        container.shutdown();
    }


    /**
     * 用户扩展处理消息
     */
    public void distributionConsumerMsg(Message message, Channel channel) {
        try {
            String str = new String(message.getBody(), StandardCharsets.UTF_8);
            RabbitData rabbitData = JSONObject.parseObject(str, RabbitData.class);
        } catch (Exception e) {
            log.debug("消息到队列失败,{}", ThrowableUtils.extractStackTrace(e));
        }
        System.out.println("3333");
    }

}
